package com.cl.blog.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.common.Const;
import com.cl.blog.entity.BAdmin;
import com.cl.blog.entity.BMenuRole;
import com.cl.blog.entity.BRole;
import com.cl.blog.exception.WebException;
import com.cl.blog.service.BAdminService;
import com.cl.blog.service.BMenuRoleService;
import com.cl.blog.mapper.BMenuRoleMapper;
import com.cl.blog.service.BRoleService;
import com.cl.blog.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author object
 * @description 针对表【b_menu_role】的数据库操作Service实现
 * @createDate 2024-03-16 15:54:45
 */
@Service
public class BMenuRoleServiceImpl extends ServiceImpl<BMenuRoleMapper, BMenuRole>
		implements BMenuRoleService {
	@Resource
	JwtUtil jwtUtil;
	@Resource
	BMenuRoleMapper bMenuRoleMapper;
	@Resource
	BAdminService bAdminService;
	@Resource
	BRoleService bRoleService;

	@Override
	public List<Integer> getMenuIds(Integer id) {

		return bMenuRoleMapper.selectAllId(id);

	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Object updateByRoleId(List<Integer> ids, HttpServletRequest request, Integer roleId) {

		String token = request.getHeader("token");
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);
		String adminId = claim.getSubject();

		// 判断是否有权限进行修改权限
		BAdmin bAdmin = bAdminService.getById(adminId);
		Assert.notNull(bAdmin, "抱歉，该用户不存在");

		BRole bRole = bRoleService.getById(bAdmin.getRoleId());
		System.out.println("是不是超管---"+bAdmin+"---"+bRole);
		if (bRole.getRole() != 0) {
			// 说明不是超管，有权限修改
			throw new WebException("抱歉，权限不足");
		}
		BRole bRole1 = bRoleService.getById(roleId);
		if (bRole1.getRole()==0){
			throw new WebException("抱歉，该用户不可修改");
		}
		// 修改权限
		// 删除数据库中多余的权限
		boolean remove = this.remove(new QueryWrapper<BMenuRole>()
				.notIn("menu_id", ids)
		);
		List<Integer> newIds = new ArrayList<>();
		// 然后将新权限保存到数据库
		for (Integer id:ids){
			BMenuRole bMenuRole = this.getById(id);
			if(bMenuRole==null){
				BMenuRole menuRole = new BMenuRole();
				menuRole.setRoleId(roleId);
				menuRole.setMenuId(id);
				boolean save = this.save(menuRole);
				if (!save){
					newIds.add(id);
				}
			}
		}

		System.out.println("所有数据-删除---->"+remove);
		System.out.println("所有数据-增加---->"+newIds);


		return null;
	}


}




